package org.jeecg.modules.wmhb.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 产品调试
 * @Author: jeecg-boot
 * @Date: 2024-10-21
 * @Version: V1.0
 */
@Api(tags = "产品调试")
@RestController
@RequestMapping("/wmhb/wmProductDebug")
@Slf4j
public class WmProductDebugController extends JeecgController<WmProductDebug, IWmProductDebugService> {
    @Autowired
    private IWmProductDebugService wmProductDebugService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;
    @Autowired
    private IWmTaskLogService wmTaskLogService;
    @Autowired
    private IWmFlowDeptService wmFlowDeptService;
    @Autowired
    private IWmTaskFlowService wmTaskFlowService;

    /**
     * 分页列表查询
     *
     * @param wmProductDebug
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "产品调试-分页列表查询")
    @ApiOperation(value = "产品调试-分页列表查询", notes = "产品调试-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmProductDebug>> queryPageList(WmProductDebug wmProductDebug,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<WmProductDebug> queryWrapper = QueryGenerator.initQueryWrapper(wmProductDebug, req.getParameterMap());
        Page<WmProductDebug> page = new Page<WmProductDebug>(pageNo, pageSize);
        IPage<WmProductDebug> pageList = wmProductDebugService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmProductDebug
     * @return
     */
    @AutoLog(value = "产品调试-添加")
    @ApiOperation(value = "产品调试-添加", notes = "产品调试-添加")
    @RequiresPermissions("wmhb:wm_product_debug:add")
    @RequestMapping(value = "/add", method = {RequestMethod.PUT,RequestMethod.POST})
    @Transactional
    public Result<String> add(@RequestBody WmProductDebug wmProductDebug) {
        WmTask wmTask = wmTaskService.getById(wmProductDebug.getWmTaskId());
        if(wmProductDebug.getCompleteQuantity() > wmTask.getQuantity()){
            return Result.error("已完成数量大于可调试数量");
        }
        wmTask.setDebugNum(wmProductDebug.getCompleteQuantity());

        //获取所有子任务(包括自己)，将子任务状态设置未已调试
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList) {
            if(wmProductDebug.getProgress().equals("100")){
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_DEBUGED);//调试完成
                wmTaskItem.setDebugNum(wmTaskItem.getQuantity());
            }
            else if(wmProductDebug.getProgress().equals("0")){
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_WAIT_DEBUG);//待调试
            }
            else{
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_DEBUGING);//调试中
            }

            wmTaskItem.setProgress(wmProductDebug.getProgress());
            wmTaskService.updateById(wmTaskItem);

            //更新当前任务为最新信息
            if (wmTask.getId().equals(wmTaskItem.getId())) {
                wmTask = wmTaskItem;
            }
        }

        //如果当前任务为根任务，任务书状态改为和根任务状态一致
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbookService.updateById(wmTaskbook);
        }

        wmProductDebugService.save(wmProductDebug);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmProductDebug
     * @return
     */
    @AutoLog(value = "产品调试-编辑")
    @ApiOperation(value = "产品调试-编辑", notes = "产品调试-编辑")
    @RequiresPermissions("wmhb:wm_product_debug:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    @Transactional
    public Result<String> edit(@RequestBody WmProductDebug wmProductDebug) {
        WmTask wmTask = wmTaskService.getById(wmProductDebug.getWmTaskId());
        if(wmProductDebug.getCompleteQuantity() > wmTask.getQuantity()){
            return Result.error("已完成数量大于可调试数量");
        }
        wmTask.setDebugNum(wmProductDebug.getCompleteQuantity());

        //获取所有子任务(包括自己)，将子任务状态设置未已调试
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
        for(WmTask wmTaskItem: wmTaskList) {
            if(!StringUtils.isEmpty(wmProductDebug.getProgress()) && wmProductDebug.getProgress().equals("100")){
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_DEBUGED);//调试完成
                wmTaskItem.setDebugNum(wmTaskItem.getQuantity());
            }
            else if(!StringUtils.isEmpty(wmProductDebug.getProgress()) && wmProductDebug.getProgress().equals("0")){
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_WAIT_DEBUG);//待调试
            }
            else{
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_DEBUGING);//调试中
            }

            wmTaskItem.setProgress(wmProductDebug.getProgress());
            wmTaskService.updateById(wmTaskItem);

            //更新当前任务为最新信息
            if (wmTask.getId().equals(wmTaskItem.getId())) {
                wmTask = wmTaskItem;
            }
        }

        //如果当前任务为根任务，任务书状态改为和根任务状态一致
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbookService.updateById(wmTaskbook);
        }

        wmProductDebugService.updateById(wmProductDebug);
        return Result.OK("添加成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "产品调试-通过id删除")
    @ApiOperation(value = "产品调试-通过id删除", notes = "产品调试-通过id删除")
    @RequiresPermissions("wmhb:wm_product_debug:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmProductDebugService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "产品调试-批量删除")
    @ApiOperation(value = "产品调试-批量删除", notes = "产品调试-批量删除")
    @RequiresPermissions("wmhb:wm_product_debug:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmProductDebugService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "产品调试-通过id查询")
    @ApiOperation(value = "产品调试-通过id查询", notes = "产品调试-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmProductDebug> queryById(@RequestParam(name = "id", required = true) String id) {
        WmProductDebug wmProductDebug = wmProductDebugService.getById(id);
        if (wmProductDebug == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmProductDebug);
    }

    /**
     * 通过任务ID查询调试记录
     */
    @ApiOperation(value = "产品调试-通过任务ID查询调试记录", notes = "产品调试-通过任务ID查询调试记录")
    @GetMapping(value = "/queryListByWmTaskId")
    public Result<List<WmProductDebug>> queryListByWmTaskId(String wmTaskId) {
        List<WmProductDebug> wmProductDebugList = wmProductDebugService.queryListByWmTaskId(wmTaskId);
        return Result.OK(wmProductDebugList);
    }

    /**
     * 任务下一流程
     * @param wmTask
     * @return
     */
    private void nextFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、下一流程
        Integer nextIndex = wmTask.getCurrentNodeIndex() + 1;
        if(nextIndex < wmFlowDeptList.size()) {

            //3、更改子任务的当前流程节点及时间信息
            WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex - 1);
            WmTaskFlow wmTaskFlowNext = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex);
            wmTaskFlowCurr.setFactEndTime(new Date());
            wmTaskFlowNext.setFactBeginTime(new Date());
            wmTaskFlowService.updateById(wmTaskFlowCurr);
            wmTaskFlowService.updateById(wmTaskFlowNext);

            //4、更新子任务当前节点
            wmTask.setCurrentNodeTime(new Date());
            wmTask.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
            wmTask.setCurrentNodeIndex(nextIndex);
            wmTaskService.updateById(wmTask);

            //5、更新任务书当前流程部门
            if (wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                wmTaskbook.setCurrentNodeIndex(nextIndex);
                wmTaskbook.setProgress(wmTask.getProgress());
                wmTaskbook.setStatus(wmTask.getStatus());
                wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
                wmTaskbookService.updateById(wmTaskbook);
            }
        }
    }

    /**
     * 任务上一流程
     * @param wmTask
     * @return
     */
    private void prevFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、上一流程
        Integer prevIndex = wmTask.getCurrentNodeIndex() - 1;
        if(prevIndex < 0){
            throw new RuntimeException("流程异常");
        }

        //3、更改子任务的当前流程节点及时间信息
        WmTaskFlow wmTaskFlowPrev = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex);
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex + 1);
        wmTaskFlowPrev.setFactEndTime(null);
        wmTaskFlowCurr.setFactBeginTime(null);
        wmTaskFlowService.updateById(wmTaskFlowPrev);
        wmTaskFlowService.updateById(wmTaskFlowCurr);

        //4、更新子任务当前节点
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
        wmTask.setCurrentNodeIndex(prevIndex);
        wmTaskService.updateById(wmTask);

        //5、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setCurrentNodeIndex(prevIndex);
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

}
